package com.hks360.car_treasure.socket;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.widget.Toast;

public class Network {

	private Context mContext;
	private final String NET_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

	public static final int NETWORN_NONE = 0;
	public static final int NETWORN_WIFI = 1;
	public static final int NETWORN_MOBILE = 2;

	public Network(Context context) {
		mContext = context;
		IntentFilter filter = new IntentFilter(NET_ACTION);
		mContext.registerReceiver(mReceiver, filter);

	}

	public void onDestroy() {
		mContext.unregisterReceiver(mReceiver);
	}

	private OnNetChangedListener mNetChangedListener;

	public void setOnNetChangedListener(OnNetChangedListener mNetChangedListener) {
		this.mNetChangedListener = mNetChangedListener;
	}

	public static interface OnNetChangedListener {

		void onNetChanged(int networkState);

	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent == null || intent.getAction() == null)
				return;
			String action = intent.getAction();
			if (action.equals(NET_ACTION)) {
				getNetworkStatus();
			}
		}
	};

	public void getNetworkStatus() {
		if (mNetChangedListener != null)
			mNetChangedListener.onNetChanged(getNetworkState());
	}

	public int getNetworkState() {
		ConnectivityManager connManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		// Wifi
		State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (state == State.CONNECTED || state == State.CONNECTING) {
			return NETWORN_WIFI;
		}
		// 2G/3G/4G
		state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		if (state == State.CONNECTED || state == State.CONNECTING) {
			return NETWORN_MOBILE;
		}
		return NETWORN_NONE;
	}
}
